#include <iostream>
#include <string>
#include <memory>

class Fruit
{
public:
    virtual void name() = 0;
};

class Apple : public Fruit
{
public:
    void name() override
    {
        std::cout << "这是一个苹果" << std::endl;
    }
};

class Pear : public Fruit
{
public:
    void name() override
    {
        std::cout << "这是一个梨" << std::endl;
    }
};

//简单工厂模式:
//优点: 简单易用
//缺点: 违背开闭原则
class FruitFactory
{
public:
    static std::shared_ptr<Fruit> create(const std::string &name)
    {
        if(name=="苹果")    return std::make_shared<Apple>();
        if(name=="梨")  return std::make_shared<Pear>();
        //... 其他水果, 一旦增加新的产品需要修改代码
        std::cout<<"参数错误"<<std::endl;
        return nullptr;
    }
};

int main(){
    std::shared_ptr<Fruit> fruit=FruitFactory::create("苹果");
    fruit->name();
    fruit=FruitFactory::create("梨");
    fruit->name();
    return 0;
}